import datetime
import os
import tempfile

import requests
from flask import Blueprint, request
from flask import abort
from flask import flash
from flask import redirect
from flask import render_template
from flask import session
from werkzeug.utils import secure_filename

from manager.app import db, worker, app, AppStore, MobileApp,AppPage
from manager.app.robot.model import Project, RobotInstance

api_robot_bp = Blueprint('robot', __name__)

'''
========= api =========
'''
#
#
# class ProjectCtrl(flask_restful.Resource):
#     def get(self):
#         return [project.to_dict() for project in Project.query.all()]
#
#     def post(self):
#         project_name = request.form['project_name']
#         project = Project()
#         project.project_name = project_name
#         db.session.add(project)
#         db.session.commit()
#         return project.to_dict()
#
#
# class RobotCtrl(flask_restful.Resource):
#     def get(self, project_id):
#         project = Project.find_project_by_id(project_id)
#         return [robot_instance.to_dict() for robot_instance in
#                 RobotInstance.query.filter_by(project_id=project_id).all()]
#
#
# class RobotDetailCtrl(flask_restful.Resource):
#
#     def get(self, app_id, robot_id):
#         robot_instance = RobotInstance.query.filter_by(app_id=app_id, id=robot_id).first()
#         return robot_instance.to_dict() if robot_instance else abort(404)
#
#     def put(self, app_id, robot_id):
#         robot_instance = RobotInstance.query.filter_by(app_id=app_id, id=robot_id).first()
#         if not robot_instance: abort(404)
#         robot_instance = RobotInstance()
#         robot_instance.robot_name = robot_instance.robot_name
#         robot_instance.project_id = app_id
#         robot_instance.robot_arguments = request.form.get('robot_arguments')
#         robot_instance.desc = request.form.get('desc')
#         robot_instance.tags = request.form.get('tags')
#         robot_instance.priority = request.form.get('priority', 0)
#         robot_instance.enabled = -1
#         db.session.add(robot_instance)
#         db.session.commit()
#         worker.start_robot(robot_instance)
#         return True


JOB_INSTANCE_FIELDS = [column.name for column in RobotInstance.__table__.columns]
JOB_INSTANCE_FIELDS.remove('id')
JOB_INSTANCE_FIELDS.remove('date_created')
JOB_INSTANCE_FIELDS.remove('date_modified')

'''
========= Router =========
'''


@app.before_request
def intercept_no_project():
    if request.path.find('/project//') > -1:
        flash("create project first")
        return redirect("/project/manage", code=302)




@app.context_processor
def utility_processor():
    def timedelta(end_time, start_time):
        '''

        :param end_time:
        :param start_time:
        :param unit: s m h
        :return:
        '''
        if not end_time or not start_time:
            return ''
        if type(end_time) == str:
            end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        if type(start_time) == str:
            start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        total_seconds = (end_time - start_time).total_seconds()
        return readable_time(total_seconds)

    def readable_time(total_seconds):
        if not total_seconds:
            return '-'
        if total_seconds < 60:
            return '%s s' % total_seconds
        if total_seconds < 3600:
            return '%s m' % int(total_seconds / 60)
        return '%s h %s m' % (int(total_seconds / 3600), int((total_seconds % 3600) / 60))

    return dict(timedelta=timedelta, readable_time=readable_time)


@app.route("/project/<project_id>")
def project_index(project_id):
    session['project_id'] = project_id
    return redirect("/project/%s/job/dashboard" % project_id, code=302)


@app.route("/project/create", methods=['post'])
def project_create():
    project_name = request.form['project_name']
    project = Project()
    project.project_name = project_name
    db.session.add(project)
    db.session.commit()
    return redirect("/project/%s/robot/deploy" % project.id, code=302)


@app.route("/project/<project_id>/delete")
def project_delete(project_id):
    project = Project.find_project_by_id(project_id)
    db.session.delete(project)
    db.session.commit()
    return redirect("/project/manage", code=302)


@app.route("/project/manage")
def project_manage():

    return render_template("project_manage.html")


@app.route("/project/<project_id>/robot/dashboard")
def robot_dashboard(project_id):
    robot_instance_list = RobotInstance.list_robots(project_id)
    return render_template("robot_dashboard.html",
                           robot_instance_list=robot_instance_list)


@app.route("/project/<project_id>/robot/deploy")
def robot_deploy(project_id):
    project = Project.find_project_by_id(project_id)
    return render_template("robot_deploy.html")


@app.route("/project/<project_id>/robot/upload", methods=['post'])
def robot_egg_upload(project_id):
    project = Project.find_project_by_id(project_id)
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.referrer)
    file = request.files['file']
    # if user does not select file, browser also
    # submit a empty part without filename
    if file.filename == '':
        flash('No selected file')
        return redirect(request.referrer)
    if file:
        filename = secure_filename(file.filename)
        dst = os.path.join(tempfile.gettempdir(), filename)
        file.save(dst)
        flash('deploy success!')
    return redirect(request.referrer)



@app.route("/appstore/manage")
def appstore_manage():
    return render_template("/appstore/manage.html", store_list=AppStore.load_app_list())

@app.route("/appstore/create", methods=['post'])
def appstore_create():
    store_name = request.form['store_name']
    store_icon = request.form['store_icon']
    store_url = request.form['store_url']
    web_site = request.form['web_site']

    store = AppStore()
    store.store_name = store_name
    store.store_icon = store_icon
    store.store_url = store_url
    store.web_site = web_site
    db.session.add(store)
    db.session.commit()
    return redirect("/appstore/manage", code=302)


@app.route("/app/manage")
def app_manage():
    return render_template("/app/manage.html", app_list=MobileApp.load_app_list())


@app.route("/app/create", methods=['post'])
def app_create():
    app_name = request.form['app_name']
    app_icon = request.form['app_icon']
    app_id = request.form['app_id']
    package_name = request.form['package_name']
    package_code = request.form['package_code']
    package_sort = request.form['package_sort']
    app = MobileApp()
    app.app_name = app_name
    app.app_icon = app_icon
    app.app_id = app_id
    app.package_name = package_name
    app.package_code = package_code
    app.package_sort = package_sort
    db.session.add(app)
    db.session.commit()
    return redirect("/app/manage", code=302)


@app.route("/app/page/<app_id>")
def app_page(app_id):
    app=MobileApp.find_app_by_id(app_id)
    print(app)
    return render_template("/app/page.html", app=app, page_list=AppPage.load_page_list(app_id))


# @app.route("/deviceScreenShot/<app_id>")
# def deviceScreenShot(app_id):
#     db.session.query(func.max(Page.id)).all()
#     doScreenShot(app_id)
#
#     return "success"
#
